import { Component, OnInit } from '@angular/core';
import { Event, Router } from '@angular/router';

import { AccountService, User } from '../../../DM/account.service';
import { BgService } from '../../../DM/background.service';
import { MenuLS, MenuItem } from '../../utils/menu';

@Component({
  selector: 'app-back',
  templateUrl: './back.component.html',
  styleUrls: ['./back.component.less']
})
export class BackComponent implements OnInit {
  isCollapsed = false;
  tabs: MenuItem[] = [];
  tabIndex = 0;
  currentUser: User = new User;

  constructor(
    private accountservice: AccountService,
    private bgService: BgService,
    private router: Router,
  ) { }

  async ngOnInit() {
    try {
      this.currentUser = await this.accountservice.getCurrentUserInfo();
      this.bgService.emitMn.subscribe(({ ite, menu }) => {
        this.newTab(ite);
      });
    } catch (err) {
      console.error('back-component-error', err);
    }
  }

  closeTab(tab: MenuItem): void {
    this.tabs.forEach((ele, index) => {
      if (ele.name == tab.name) {
        this.tabs.splice(index, 1);
        return;
      }
    });
    if (this.tabs.length == this.tabIndex)--this.tabIndex; // 这个组件在这里有bug，需要手动设置一下
    this.tabs.length > 0 && this.router.navigate([this.tabs[this.tabIndex].path[0]]);
  }

  newTab(tab: MenuItem): void {
    let flag: boolean = false;
    this.tabs.forEach((ele, index) => {
      if (ele.name == tab.name) { // 存在
        flag = true;
        this.tabIndex = index;
        return;
      }
    });
    if (!flag) { // 不存在
      this.tabs.push(tab);
      this.tabIndex = this.tabs.length - 1;
    }
  }

}
